package cDB

import (
	"encoding/json"

	"github.com/tidwall/gjson"

	"gitee.com/csingo/cLog"

	"gitee.com/csingo/cDB/drivers"
	"gitee.com/csingo/cDB/drivers/clickhouse"
	"gitee.com/csingo/cDB/drivers/mongo"
	"gitee.com/csingo/cDB/drivers/mysql"
	"gitee.com/csingo/cDB/drivers/redis"
	"gitee.com/csingo/cDB/drivers/sqlite"
	"gitee.com/csingo/cDB/drivers/tdengine"
)

const (
	DatabaseConfigName = "DatabaseConf"
)

type DatabaseConf struct {
	Connections map[string]drivers.DriverInterface `json:"connections"`
}

func (i *DatabaseConf) ConfigName() string {
	return DatabaseConfigName
}

func (i *DatabaseConf) Decode(data string) error {
	var err error
	if i.Connections == nil {
		i.Connections = make(map[string]drivers.DriverInterface)
	}
	for k := range i.Connections {
		delete(i.Connections, k)
	}
	gjson.Get(data, "connections").ForEach(func(key, value gjson.Result) bool {
		var db drivers.DriverInterface
		switch drivers.DBDriver(value.Get("driver").String()) {
		case mysql.Driver:
			db = &mysql.Connection{}
		case redis.Driver:
			db = &redis.Connection{}
		case clickhouse.Driver:
			db = &clickhouse.Connection{}
		case tdengine.Driver:
			db = &tdengine.Connection{}
		case sqlite.Driver:
			db = &sqlite.Connection{}
		case mongo.Driver:
			db = &mongo.Connection{}
		default:
			cLog.WithContext(nil, map[string]any{
				"key":    key,
				"driver": value.Get("driver").String(),
			}, []cLog.Option{
				cLog.IncludePaths{},
			}).Fatalln("数据库驱动不支持")
		}
		err = json.Unmarshal([]byte(value.Raw), db)
		if err == nil {
			i.Connections[key.String()] = db
		}

		return true
	})
	return err
}

var database_config *DatabaseConf
